<template>
  <div class="page-wapper">
    <!-- 组织架构 -->
    <div class="container" style="padding: 0">
      <!-- 顶部 -->
      <header class="group_header">
        <div class="t_c">组织架构</div>
      </header>
      <!-- 主体 -->
      <div class="group_part">
        <div class="group_content">
          <!--  -->
          <div v-for="(item, i) in groupViewData" :key="i" class="group_row">
            <div v-for="(cell, j) in item" :key="j" class="group_cell_wrapper">
              <div
                v-for="(it, k) in cell"
                :key="k"
                :id="`group_cell_${it.id}`"
                class="group_cell top_line"
                :cell-level="it.level"
              >
                {{ it.name }}
              </div>
              <!-- <div class="link_line top"></div> -->
            </div>
          </div>
          <!--  -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  getCurrentInstance,
  onActivated,
  toRefs,
  computed,
  watch,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";

export default {
  name: "GroupManage",
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;

    const groupData = ref([
      {
        id: 100,
        name: "技术部",
        children: [
          {
            id: 101,
            name: "前端组",
            children: [
              {
                id: 103,
                name: "前端小组A",
                children: [
                  { id: 105, name: "前端小组AA" },
                  { id: 106, name: "前端小组AB" },
                ],
              },
              {
                id: 104,
                name: "前端小组B",
                children: [
                  { id: 107, name: "前端小组BA" },
                  { id: 108, name: "前端小组BB" },
                ],
              },
            ],
          },
          {
            id: 102,
            name: "立团组",
            children: [
              {
                id: 109,
                name: "立团小组A",
                children: [
                  { id: 113, name: "立团小组AA" },
                  { id: 114, name: "立团小组AB" },
                ],
              },
              {
                id: 110,
                name: "立团小组B",
                children: [
                  { id: 111, name: "立团小组BA" },
                  { id: 112, name: "立团小组BB" },
                ],
              },
            ],
          },
        ],
      },
    ]);

    const marginViewData = ref([]);

    const LAST_LEVEL_CELL_MARGIN = 40;

    const groupViewData = computed(() => {
      const viewData = [];
      const chachObj = {};
      const fn = (list, level) => {
        if (list && Array.isArray(list)) {
          const chachKey = "a_" + level;
          if (!chachObj[chachKey]) {
            chachObj[chachKey] = [];
          }
          const innerList = [];
          list.forEach((item) => {
            item.level = level;
            if (item.name) {
              const newObj = cloneDeep(item);
              if (newObj.children) {
                delete newObj.children;
              }
              innerList.push(newObj);
            }
          });
          // 缓存起来
          chachObj[chachKey].push(innerList);
          list.forEach((item, index) => {
            if (item.children) {
              fn(item.children, level + 1);
            }
          });
        }
      };
      fn(groupData.value, 0);
      Object.keys(chachObj).forEach((key, index) => {
        if (key === "a_" + index) {
          viewData.push(chachObj[key]);
        }
      });
      console.log("computed ===>", viewData);
      console.log("computed ===>groupData.value", groupData.value);
      return viewData;
    });

    // 计算边距
    const computeMarginViewData = (viewData) => {
      nextTick(() => {
        // newVal.forEach((item) => {});
        // 获取所有 group_cell 元素宽度，缓存起来，避免重复获取
        const groupCellWidthChache = {};
        const groupCellElList = document.querySelectorAll(".group_cell");
        // console.log("groupCellElList ==>", groupCellElList);
        for (let i = 0; i < groupCellElList.length; i++) {
          const groupCellId = groupCellElList[i].id;
          // console.log("groupCellId ==>", groupCellId);
          groupCellWidthChache[groupCellId] = groupCellElList[i].offsetWidth;
        }
        console.log("groupCellWidthChache ==>", groupCellWidthChache);
        // 获取元素宽度
        const getGroupCellWidth = (cell) => {
          return groupCellWidthChache[`group_cell_${cell.id}`];
        };

        const newViewData = cloneDeep(viewData).reverse();
        newViewData.forEach((item, i) => {
          item.forEach((cell, j) => {
            const cellLeftList = [];
            let groupCellWrapperWidth = 0;
            cell.forEach((it, k) => {
              groupCellWrapperWidth +=
                getGroupCellWidth(it) + LAST_LEVEL_CELL_MARGIN;
              if (i === 0) {
                if (j === 0) {
                  if (k === 0) {
                    cellLeftList.push(0);
                  } else {
                    const cellLeft =
                      cellLeftList[k - 1] +
                      getGroupCellWidth(cell[k - 1]) +
                      LAST_LEVEL_CELL_MARGIN;
                    cellLeftList.push(cellLeft);
                  }
                } else {
                  newViewData[i][j - 1][k];
                  if (k === 0) {
                    const cellLeft =
                      cellLeftList[cellLeftList.length - 1] +
                      getGroupCellWidth(cell[k - 1]) +
                      LAST_LEVEL_CELL_MARGIN;
                    cellLeftList.push(cellLeft);
                  }
                }
              }
            });
            console.log("cellLeftList ===>6666", cellLeftList);
          });
        });
      });
    };

    watch(
      () => groupViewData.value,
      (newVal) => {
        console.log("groupViewData变了===>", newVal);
        computeMarginViewData(newVal);
      },
      { deep: true, immediate: true }
    );

    // 删除单个内容
    const deleteTableDataMethod = (row) => {};

    // 删除内容接口
    const deleteTableData = (ids) => {
      tableState.tableLoading = true;
      $api.report
        .deleteReport({
          ids,
        })
        .then((res) => {
          console.log("res => ", res);
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // onActivated(() => {
    // });

    return {
      groupData,
      groupViewData,
      deleteTableDataMethod,
    };
  },
};
</script>

<style lang="less" scoped>
.group_header {
  border-bottom: 1px solid #eee;
  padding: 20px;
}

.group_part {
  flex: 1;
  overflow: auto;
  .group_content {
    position: relative;
    padding: 20px;
  }
  .group_row {
    // display: flex;
    // justify-content: center;
    // align-items: center;
    position: relative;
    height: 63px;
  }
  .group_cell_wrapper {
    // position: relative;
    // display: flex;
    // flex-shrink: 0;
    // justify-content: center;
    // align-items: center;
    // padding: 20px;
  }
  .link_line {
    position: absolute;
    top: 0;
    left: 50%;
    z-index: 0;
    height: 100%;
    width: 500px;
    transform: translateX(-50%);
    box-sizing: border-box;
    &.top {
      border-top: 2px solid #409eff;
    }
    &.bottom {
      border-bottom: 2px solid #409eff;
    }
  }
  .group_cell {
    border: 1px solid #409eff;
    padding: 10px 20px;
    border-radius: 4px;
    position: absolute;
    z-index: 1;
    // & + .group_cell {
    //   margin-left: 40px;
    // }
    &.top_line::before {
      display: block;
      content: "";
      position: absolute;
      top: 0;
      left: 50%;
      width: 2px;
      background: #409eff;
      height: 20px;
      transform: translate(-50%, -100%);
    }
    &.bottom_line::after {
      display: block;
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      width: 2px;
      background: #409eff;
      height: 20px;
      transform: translate(-50%, 100%);
    }
  }
}
</style>
